package validator;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import command.UserForm;

@Component
public class UserFormValidator implements Validator {

	@Override
	public boolean supports(Class<?> clazz) {
		return UserForm.class.isAssignableFrom(clazz);
	}
	
	@Override
	public void validate(Object target, Errors errors) {
		UserForm form = (UserForm) target;
		if(form.getPassword()==null || form.getPassword2()==null){
			errors.rejectValue("password", "empty");
		}else if(form.getPassword().isEmpty() || form.getPassword2().isEmpty()){
			errors.rejectValue("password", "empty");
			errors.rejectValue("password2", "empty");
		}else if(form.getPassword().length()>16 || form.getPassword2().length()>16){
			errors.rejectValue("password", "tooLong");
			errors.rejectValue("password2", "tooLong");			
		}else if(!form.getPassword().equals(form.getPassword2())){
			errors.rejectValue("password2", "confirmation");
		}
		if(form.getEmail()==null || form.getEmail().isEmpty()){
			errors.rejectValue("email", "empty");
		}else if(!form.getEmail().isEmpty()){
			if(!form.getEmail().matches("^[\\w\\-\\_\\+]+(\\.[\\w\\-\\_]+)*@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$")){
				errors.rejectValue("email", "invalid");
			}else if(form.getEmail().length()>100){
				errors.rejectValue("email", "tooLong");
			}
		}
		
		if (form.getLastName()==null || form.getLastName().isEmpty()){
			errors.rejectValue("lastName", "empty");
		}else if(form.getLastName().length()>100){
			errors.rejectValue("lastName", "tooLong");
		}
		if (form.getName()==null || form.getName().isEmpty()){
			errors.rejectValue("name", "empty");
		}else if(form.getName().length()>100){
			errors.rejectValue("name", "tooLong");
		}
		if (form.getDocNumber()==null||form.getDocNumber().isEmpty()){
			errors.rejectValue("docNumber", "empty");
		}else if(form.getDocNumber().length()>50){
			errors.rejectValue("docNumber", "tooLong");
		}
	}
}